/**
 * 修改头像
 */
'use strict';
app.controller('UpdateUserImageCtrl', ["$scope","$rootScope","$state",function($scope,$rootScope, $state) {
    $scope.isChanged = false;
    $scope.$on('$ionicView.enter', function(){
        $rootScope.hideMainBar =true;
        var URL = window.URL || window.webkitURL;
        var blobURL;
        if(URL && $rootScope.userImg){
            var files = $rootScope.userImg;
            var file;
            fileName = files.name;
            if (!$image.data('cropper')) {
                return;
            }
            if (files && files.length) {
                file = files[0];
                if (/^image\/\w+$/.test(file.type)) {
                    blobURL = URL.createObjectURL(file);
                    $image.one('built.cropper', function () {
                        // Revoke when load complete
                        URL.revokeObjectURL(blobURL);
                    }).cropper('reset').cropper('replace', blobURL);
                    $inputImage.val('');
                } else {
                    window.alert('Please choose an image file.');
                }
            }
        }else{

        }
    });
    $scope.goUserDetail = function (){
        $state.go('UserDetail')
    }
    var $image = $('#updateimage');
    //var imgurl = "http://test.lbwan.com/res/upload/images/game/icon/p1a38nre2b1oi112391luao60152cf.png"
    var fileName = "";
    var options = {
        aspectRatio: 1 / 1,
        preview: '.img-preview',
        crop: function (e) {
        }
    };
    //$image.attr("src", imgurl);
    // Cropper
    $image.on({
        'build.cropper': function (e) {
        },
        'built.cropper': function (e) {
        },
        'cropstart.cropper': function (e) {
        },
        'cropmove.cropper': function (e) {
        },
        'cropend.cropper': function (e) {
        },
        'crop.cropper': function (e) {
        },
        'zoom.cropper': function (e) {
        }
    }).cropper(options);
    // Buttons
    if (!$.isFunction(document.createElement('canvas').getContext)) {
        $('button[data-method="getCroppedCanvas"]').prop('disabled', true);
    }

    if (typeof document.createElement('cropper').style.transition === 'undefined') {
        $('button[data-method="rotate"]').prop('disabled', true);
        $('button[data-method="scale"]').prop('disabled', true);
    }
    // Options
    $('.docs-toggles').on('change', 'input', function () {
        var $this = $(this);
        var name = $this.attr('name');
        var type = $this.prop('type');
        var cropBoxData;
        var canvasData;

        if (!$image.data('cropper')) {
            return;
        }

        if (type === 'checkbox') {
            options[name] = $this.prop('checked');
            cropBoxData = $image.cropper('getCropBoxData');
            canvasData = $image.cropper('getCanvasData');

            options.built = function () {
                $image.cropper('setCropBoxData', cropBoxData);
                $image.cropper('setCanvasData', canvasData);
            };
        } else if (type === 'radio') {
            options[name] = $this.val();
        }
        $image.cropper('destroy').cropper(options);

    });


    // Methods
    $('.docs-buttons').on('click', '[data-method]', function () {
        var $this = $(this);
        var data = $this.data();
        var $target;
        var result;

        if ($this.prop('disabled') || $this.hasClass('disabled')) {
            return;
        }

        if ($image.data('cropper') && data.method) {
            data = $.extend({}, data); // Clone a new one

            if (typeof data.target !== 'undefined') {
                $target = $(data.target);

                if (typeof data.option === 'undefined') {
                    try {
                        data.option = JSON.parse($target.val());
                    } catch (e) {
                        console.log(e.message);
                    }
                }
            }

            result = $image.cropper(data.method, data.option, data.secondOption);

            switch (data.method) {
                case 'scaleX':
                case 'scaleY':
                    $(this).data('option', -data.option);
                    break;

                case 'getCroppedCanvas':
                    if (result) {

                        // Bootstrap's Modal
                        $('#getCroppedCanvasModal').modal().find('.modal-body').html(result);

                    }

                    break;
            }

            if ($.isPlainObject(result) && $target) {
                try {
                    $target.val(JSON.stringify(result));
                } catch (e) {
                    console.log(e.message);
                }
            }

        }
    });
    var $inputImage = $('#inputImage');
    var URL = window.URL || window.webkitURL;
    var blobURL;

    if (URL) {
        $inputImage.change(function () {
            var self = this ;
            $scope.$apply(function () {
                $scope.isChanged = true;
                var files = self.files;
                var file;
                fileName = files.name;
                if (!$image.data('cropper')) {
                    return;
                }
                if (files && files.length) {
                    file = files[0];
                    if (/^image\/\w+$/.test(file.type)) {
                        blobURL = URL.createObjectURL(file);
                        $image.one('built.cropper', function () {
                            // Revoke when load complete
                            URL.revokeObjectURL(blobURL);
                        }).cropper('reset').cropper('replace', blobURL);
                        $inputImage.val('');
                    } else {
                        window.alert('Please choose an image file.');
                    }
                }
            });

        });
    } else {
        $inputImage.prop('disabled', true).parent().addClass('disabled');
    }
    //$scope.$on('$ionicView.enter', function(scopes, states){
    //    //onEnter(states);
    //});
    //
    //$scope.$on('$ionicView.leave', function(scopes, states){
    //    //onExit(states);
    //});
    $scope.updateImgEnter= function () {
        var src = $image.eq(0).attr("src");
        var canvasdata = $image.cropper("getCanvasData");
        var cropBoxData = $image.cropper('getCropBoxData');
        var canvas = $image.cropper("getCroppedCanvas");
        var data = canvas.toDataURL('image/jpeg', 0.2);
        var encodeData = data.split(',')[1];
        var decodedData = window.atob(encodeData);
        var ia = new Uint8Array(decodedData.length);
        for (var i = 0; i < decodedData .length; i++) {
            ia[i] = decodedData .charCodeAt(i);
        };
        try{
            var blob = new Blob([ia], {type:"image/jpeg"});
        }catch(e){
            return;
        }
        if(blob){
            console.log(blob.size/1024/1000)
            var fd = new FormData();
            fd.append('userId', "");
            fd.append('token', "");
            fd.append('scale', "0.5");
            fd.append('file', blob, "blob.jpeg")
            var url = "lbs/user/uploadImage.json";
          alert("以获取图片，未发送给服务器，需要steam数据")
            //$.ajax({
            //    url: url,
            //    type:"POST",
            //    data:fd,
            //    processData: false,  // 告诉jQuery不要去处理发送的数据
            //    contentType: false,  // 告诉jQuery不要去设置Content-Type请求头
            //    success:function(data) {
            //        //console.log(data);
            //        //alert(data)
            //        //$state.go('UserDetail')
            //        if(data.code == 'success'){
            //            $state.go('UserDetail')
            //        }
            //    },
            //    error: function(error){
            //        console.log(error)
            //    }
            //});
        }else{
        }
    }
}]);
